<template>
	<view class="home-container">
		<view class="header-container">
			<view class="equitment-num box">
				<view class="equitment-top">
					<view class="equitment-num-title">设备总数</view>
					<view class="equitment-num-content">{{statistics.total}}</view>
				</view>
				<view class="equitment-btm">
					<view class="equitment-btm-left">
						<view class="equitment-btm-title">在线设备</view>
						<view class="equitment-btm-content">{{statistics.onlineDevices}}</view>
					</view>
					<view class="equitment-btm-right">
						<view class="equitment-btm-title">待机设备</view>
						<view class="equitment-btm-content">{{statistics.offlineEquipment}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="phenomena-container box">
			<view class="phenomena-tabs">
				<view class="phenomena-tabs-box">
					<view @click="changeTab(item)" class="tabs-item" :class="{'activeTab':activeTab == item.productType}" v-for="(item,index) in phenomenaTabs" :key='index'>{{item.title}}</view>
				</view>
				<view class="tab-right-icon" @click="toEquipList">
					<uni-icons type="right" size="20" color="#A1A3A5"></uni-icons>
				</view>
			</view>
			<view class="equipmen-type">
				<picker mode="selector" :range="phenomenaEquipList" range-key="name" @change="handerChangePhenomena">
					<view class="equipmen-type-left">{{currphenomenaEquip ?  currphenomenaEquip : '设备名称'}} <uni-icons type="bottom" size="12" color="#A1A3A5"></uni-icons>
					</view>
				</picker>
				
				<view class="equipmen-type-time">{{newTime}} 更新</view>
			</view>
			<!-- <view class="notice">
				<uni-notice-bar single show-close show-icon text="光照强度超过50Lux，风速超过4m/s，降雨量超过40m" />
			</view> -->
			<view class="phenomena-weather">
				<view v-for="(item,index) in weatherList" :key="index" class="phenomena-weather-item"
					:class="{'weather-active':activeTabWeather == index}" @click="handleWeather(item,index)">
					<view class="item-desc">
						<view class="item-title">{{ item.title }}</view>
						<view class="item-content">{{ item.content }}</view>
					</view>
				</view>
			</view>
			<view class="phenomena-chart" >
				<uni-datetime-picker  style="width: 80%;" v-model="range" type="daterange" @maskClick="maskClick" @change="changeDate" />
				<echarts ref="echarts" v-if="!isNoChartData" :option="option" canvasId="echarts1" style="width: 100%;height: 90%;" ></echarts>
				<view class="no-data" v-else style="width:100%;height: 100%;">
					暂无数据
				</view>
				<!-- <view v-if="!isNoChartData">
					<echarts ref="echarts" :option="option" canvasId="echarts1" style="width: 100%;height: 90%;" ></echarts>
				</view>
				<view class="no-data" v-else style="width:100%;height: 100%;">
					暂无数据
				</view> -->
			</view>
			
		</view>
		<view class="insect-container box">
			<view class="phenomena-tabs">
				<view class="phenomena-tabs-box">
					<view @click="changeTabInsect(item)" class="tabs-item" 
					:class="{'activeTab':activeTabInsect == item.productType}" 
					v-for="(item,index) in insectTabs" :key="index">{{item.title}}</view>
				</view>
				<view class="tab-right-icon" @click="toEquipListInsect">
					<uni-icons type="right" size="20" color="#A1A3A5"></uni-icons>
				</view>
			</view>
			<view class="equipmen-type" >
				<picker mode="selector" :range="insectEquipList" range-key="name" @change="handerChangeInsect">
					<view class="equipmen-type-left">{{currpinsectEquip ?  currpinsectEquip : '设备名称'}} <uni-icons type="bottom" size="12" color="#A1A3A5"></uni-icons>
					</view>
				</picker>
				<view class="equipmen-type-time" v-if='swiperList.length > 0'>{{getCurrTime(swiperList[0].createTime)}} 更新</view>	
				<view class="equipmen-type-time" v-if='swiperList.length === 0'>---更新</view>	
			</view>
			<view v-if="insectEquipList.length > 0">
				<view class="notice" v-if="activeTabInsect == '001'">
					<uni-notice-bar single show-close show-icon text="始见金龟子超过10头，瓢虫超过" />
				</view>
				<view :class="presetList.length > 0 ? 'tags' : 'nodata'" v-if="activeTabInsect == '002'">
					<template v-if="presetList.length">
						<view class="tags-item" @click="changePreset(item,index)" :class="{'activeTag':activeTag == index}" v-for="(item,index) in presetList" :key="index">{{item.pointName}}</view>
					</template>
					<view class="no-data" v-else style="width:100%;height: 100%;">
						暂无数据
					</view>
				</view> 
				<view class="swiper" v-if="presetList.length">
						<swiper style="height: 100%;" class="swiper-box" :current="swiperDotIndex" :indicator-dots="true">
							<swiper-item v-for="(item, index) in swiperList" :key="index">

								<!-- <img :src="$getImageSrc('insect.png')" alt="" v-if="activeTabInsect == '001'" /> -->
								<!-- <img :src="item.url" alt="" /> -->
								<image :src="item.url" mode="widthFix" />
								{{item.url}}
								<view class="swiper-item" :class="'swiper-item' + index">
									<text style="color: #fff; font-size: 32px;">{{index+1}}</text>
								</view>
							</swiper-item>
						</swiper>
				</view>
			</view>
			<view class="no-data" v-else style="width:100%;height: 400rpx;color: #a1a3a5;">
				暂无数据
			</view>
		</view>
		
	</view>
</template>

<script>
	import echarts from '@/components/echarts-uniapp/echarts-uniapp.vue'
	import {equipmentPage,obtainDeviceData,getDetailedData,equipmentStatistics,
	getDataDetailInfo,queryPreset,getPresetFile,
	getInsectSentimentFile
	} from '../../untils/api.js'
	import {formatTimestamp} from '../../untils/pubic.js'
	export default {
		components: {
			echarts
		},
		data() {
			return {
				range: [],
				statistics:{},
				currphenomenaEquip:'',
				currpinsectEquip:'',
				phenomenaEquipList:[],
				insectEquipList:[],
				option: {},
				activeTag:0,
				activeTab:'003',
				activeTabWeather:0,
				phenomenaTabs:[
					{title:'气象数据',productType:'003'},
					{title:'墒情数据',productType:'004'},
				],
				insectTabs:[
					{title:'最新虫情',productType:'001'},
					{title:'最新苗情',productType:'002'},
					{title:'最新孢子',productType:'005'},
				],
				swiperDotIndex:1,
				activeTabInsect: '002',
				weatherList: [],
				newTime:'',
				newTimeInsect:'',
				currRow:{},
				isNoChartData:false,
				presetList:[],
				swiperList:[]
			}
		},
		methods:{
			getCurrTime(time){
				console.log(time)
				if(!time){
					return '----'
				}
				return formatTimestamp(time)
			},
			async changePreset(item,index) {
				this.activeTag = index
				let presetCode = ''
				if(index == this.presetList.length - 1) {
					presetCode = ''
				}else {
					presetCode = item.pointCode
				}
				const res = await getPresetFile({presetCode:presetCode,deviceCode:item.deviceId})
				this.swiperList = res.data?.list || []
			},
			// 查询点位
			async queryPreset(deviceId) {
				// console.log(deviceId,'deviceId');
				const res = await queryPreset({deviceId:deviceId})
				// const res = await queryPreset({deviceId:'AK06047PAJ9EC45'})
				this.presetList = res.data ? res.data : []
				if(!this.presetList.length) return
				this.presetList.push({pointName:'全部',deviceId:res.data[0].deviceId})
				this.changePreset(this.presetList[0],0)
			},
			async initChart() {
				this.option = {}
				uni.showLoading({
					title:'加载中',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				})
				if(this.phenomenaEquipList.length === 0){
					this.isNoChartData = true
					uni.hideLoading()
					return false
				}
				const params = {
					circuit:this.currRow.circuit,
					equipmentCode:this.phenomenaEquipList[0].equipmentCode,
					startingTime:this.range[0],
					endTime:this.range[1],
				}
				const res = await getDataDetailInfo(params)
				uni.hideLoading()
				if(res.data.length <= 0) {
					this.isNoChartData = true
				} else {
					this.isNoChartData = false
				}
				const chartData = res.data.map(item => item.newestData)
				const chartTime = res.data.map(item => item.newestTime)
				let title = {}
				if(chartData.length > 0) {
					title =  {
						text: this.currRow.name,
						textStyle: {
							fontSize: 14 // 设置标题文字的大小为24
						},
					}
				}else {
					title = {
						text: '暂无数据',
						left: 'center',
						top: 'middle',
						textStyle: {
							color: '#A1A3A5',
							fontSize: 16
						},
					}
				}
				this.option =  {
					title: title,
					grid: {
					        // 调整图表的位置和大小，top 表示图表顶部与容器顶部的距离
					        top: '15%', 
					        // 其他 grid 属性，如 left、right、bottom、containLabel 等可根据需要设置
					        left: '3%',
					        right: '4%',
					        bottom: '15%',
					        containLabel: true
					      },
					xAxis: {
						type: 'category',
						data: chartTime,
						show:chartData.length > 0 ? true : false
					},
					yAxis: {
						show:chartData.length > 0 ? true : false,
						type: 'value',
						axisLabel: {
							showMinLabel: true, // 显示最小值标签
							showMaxLabel: true, // 显示最大值标签
							interval: 'auto' // 自动调整间隔
						}
					},
					series: [{
						data: chartData,
						type: 'line',
						color: '#43C722'
					}]
				};
			},
			getDateSevenDaysAgo() {
				const today = new Date(); // 获取当前日期
			    const sevenDaysAgo = new Date(today); // 复制当前日期
			    sevenDaysAgo.setDate(today.getDate() - 7); // 设置为前第七天
				const year = today.getFullYear(); // 获取年份
				const month = String(today.getMonth() + 1).padStart(2, '0'); // 获取月份（补零）
				const day = String(today.getDate()).padStart(2, '0'); // 获取日期（补零）
								
				// 格式化为 YYYY-MM-DD
				const currDate= `${year}-${month}-${day}`;
			
			    // 格式化为 YYYY-MM-DD
			    const formattedDate = sevenDaysAgo.toISOString().split('T')[0];
			    return [formattedDate,currDate];
			},
			changeDate(e) {
				console.log("-change事件:", e);
				this.initChart()
			},
			maskClick(e) {
				// this.single = e;
			},
			// 气象设备下拉
			handerChangePhenomena(val) {
				console.log(val);
				if(!this.phenomenaEquipList[val.detail.value]?.equipmentCode) return false;
				const equip = this.phenomenaEquipList[val.detail.value].equipmentCode
				this.getDetailedDataFn(equip)
				this.currphenomenaEquip = this.phenomenaEquipList[val.detail.value].name
			},
			handerChangeInsect(val) {
				this.currpinsectEquip = this.insectEquipList[val.detail.value].name
				this.getSwiperList(this.insectEquipList[val.detail.value].equipmentCode)
				// this.queryPreset(this.insectEquipList[0].equipmentCode)
				// this.queryPreset(this.insectEquipList[val.detail.value].equipmentCode)
			},
			// 获取设备数据信息
			async getDetailedDataFn(code) {
				// cosnt res = await getDetailedData(code)
				const res = await getDetailedData(code)
				if(res.code == 200) {
					this.newTime = res.data.length ? formatTimestamp(res.data[0].newestTime) : ''
					this.currRow = res.data.length ? res.data[this.activeTabWeather] : []
					this.weatherList = res.data.map(item => {
						return {
							...item,
							title:`${item.newestData}${item.unit}`,
							content:item.name
						}
					})
				this.initChart()
				}
				uni.hideLoading()
			},
			async getEquipmentList() {
				uni.showLoading({
					title:'加载中',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				})
				const params ={
					pageNo:1,
					pageSize:100,
					productType:this.activeTab
				}
				const res = await equipmentPage(params)
				uni.hideLoading()
				
				if(res.code == 200) {
					if(res.data.list.length) {
						this.phenomenaEquipList = res.data.list
						this.currphenomenaEquip = res.data.list[0].name
						
						this.getDetailedDataFn(res.data.list[0]?.equipmentCode)
					}else {
						this.currphenomenaEquip = ''
						this.phenomenaEquipList = []
						this.isNoChartData = true
					}
					
					
				}
			},
			async getEquipmentListInsect() {
				uni.showLoading({
					title:'加载中',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				})
				const params ={
					pageNo:1,
					pageSize:100,
					productType:this.activeTabInsect
				}
				const res = await equipmentPage(params)
				
				if(res.code == 200) {
					if(res.data.list.length) {
						this.insectEquipList = res.data.list
						this.currpinsectEquip = res.data.list[0].name
						
					}else {
						this.currpinsectEquip = ''
						this.insectEquipList = []
					}
					this.getSwiperList(this.insectEquipList[0]?.equipmentCode)	
				}
				uni.hideLoading()
				
			},
			getSwiperList(code){
                    // 区分 虫情  苗情  孢子
					if(this.activeTabInsect === '001' || this.activeTabInsect === '005'){
                     this.getInsectSentimentFileInfo(code)
					}
					if(this.activeTabInsect === '002'){
                       this.queryPreset(code)
					}
					if(this.activeTabInsect === '005'){
						
					}
			},
			async getInsectSentimentFileInfo(code){
				let params = {
					deviceCode: code,
					pageNo:1,
					pageSize:10
				};
               const res = await getInsectSentimentFile(params)
			   this.presetList = [{}]
			   this.swiperList = res.data.list
			},
			toEquipList() {
				const title = this.phenomenaTabs.find(item => item.productType == this.activeTab).title
				uni.navigateTo({
					url:`/subpackage/meteorologicalMonitoring/index?title=${title}&productType=${this.activeTab}`
				})
			},
			toEquipListInsect() {
				if(this.activeTabInsect == '001') {
					uni.navigateTo({
						url:`/subpackage/meteorologicalMonitoring/insect?title=${'虫情监控'}&productType=${this.activeTabInsect}`
					})
				}
                if(this.activeTabInsect == '002') {
					uni.navigateTo({
						url:`/subpackage/meteorologicalMonitoring/miaoqing?title=${'苗情监测'}&productType=${this.activeTabInsect}`
					})
				}
				if(this.activeTabInsect == '005') {
					
				}
				return false
				if(this.activeTabInsect == '002') {
					uni.navigateTo({
						url:`/subpackage/meteorologicalMonitoring/miaoqing?title=${'苗情监测'}&productType=${this.activeTabInsect}`
					})
				}else {
					const title = this.insectTabs.find(item => item.productType == this.activeTabInsect).title
					uni.navigateTo({
						url:`/subpackage/meteorologicalMonitoring/index?title=${title}&productType=${this.activeTabInsect}`
					})
				}
				
			},
			changeTab(item) {
				this.activeTabWeather = 0
				this.activeTab = item.productType
				this.getEquipmentList()
			},
			changeTabInsect(item) {
				this.activeTabInsect = item.productType
				this.swiperList = []
				this.getEquipmentListInsect()
			},
			handleWeather(item,index) {
				console.log(item);
				this.activeTabWeather = index
				this.newTime = formatTimestamp(item.newestTime)
				this.currRow = item
				this.initChart()
				// uni.navigateTo({
				// 	url:'/subpackage/airTemperature/index'
				// })
			},
			// 获取首页设备数量
			getHomeEquipmentStatistics() {
				equipmentStatistics().then(res => {
					console.log(res);
					this.statistics = res.data
				})
			},
			
		},
		mounted() {
				
		},
		onLoad() {
			this.range = this.getDateSevenDaysAgo()
			
			this.getEquipmentList()
			this.getEquipmentListInsect()
			this.getHomeEquipmentStatistics()
			
		}
	}
</script>

<style lang="scss" scoped>
	.home-container {
		height: 100vh;
		overflow-y: auto !important;
		background-color: #f3f4f4;
		padding-top: 0 10px;

		.header-container {
			width: 100%;
			height: 150px;
			background-color: #ebfaef;
		}

		.equitment-num {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			height: 140px;
			background: #33C163;
			background-image: url('@/static/image/men.png');
			background-repeat: no-repeat;
			background-size: 120px 120px;
			background-position: 205px 18px;
			border-radius: 8px;

			.equitment-top {
				color: #fff;
				margin: 20px;

				.equitment-num-title {
					font-weight: 400;
					font-size: 14px;
				}

				.equitment-num-content {
					font-weight: 600;
					font-size: 32px !important;
					margin-top: 6px;
				}
			}

			.equitment-btm {
				margin: 0 auto;
				margin-bottom: 4px;
				width: 96%;
				height: 40px;
				background: #FFFFFF;
				border-radius: 6px;
				display: flex;
				align-items: center;

				.equitment-btm-title {
					font-size: 12px;
					color: #535557;
				}

				.equitment-btm-content {
					font-weight: 600;
					font-size: 16px;
					color: #181D21;
					margin-left: 57px;
				}

				.equitment-btm-left {
					position: relative;
					margin-left: 16px;
					width: 50%;
					display: flex;
					align-items: center;

					&::after {
						position: absolute;
						right: 0;

						content: '';
						width: 1px;
						height: 16px;
						background: #EEEEEE;
					}
				}

				.equitment-btm-right {
					margin-left: 16px;
					width: 50%;
					display: flex;
					align-items: center;
				}
			}
		}

		.phenomena-container {
			box-sizing: border-box;
			padding: 16px 8px;
			// height: 468px;
			background: #fff;
			box-shadow: 0px 3px 12px 0px rgba(0, 0, 0, 0.02);
			border-radius: 8px 8px 8px 8px;

			.phenomena-tabs {
				justify-content: space-between;
				display: flex;
				align-items: center;
				height: 20px;

				.phenomena-tabs-box {
					display: flex;
					align-items: center;
					height: 20px;
				}

				.tabs-item {
					width: 60px;
					height: 15px;
					font-weight: 500;
					font-size: 15px;
					color: #535557;
					line-height: 15px;
					margin-right: 16px;
				}

				.activeTab {
					position: relative;
					color: #00B23C;

					&::after {
						position: absolute;
						bottom: -4px;
						left: 0;
						content: '';
						width: 59px;
						height: 2px;
						background: #00B23C;
						border-radius: 2px 2px 2px 2px;
					}
				}
			}

			.equipmen-type {
				margin-top: 12px;
				margin-bottom: 12px;
				height: 12px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 12px;
				.equipmen-type-left {
					font-size: 12px;
					color: #181B21;
				}

				.equipmen-type-time {
					font-size: 12px;
					color: #A1A3A5;
				}
			}

			.notice {
				margin-top: 10px;
			}

			.phenomena-weather {
				 display: grid;
				            grid-template-columns: repeat(3,1fr);
				            gap: 8rpx;
				            /* 设置左对齐 */
				            justify-content: start;

				.phenomena-weather-item {
					// width: 32%;
					height: 60px;
					background: #F5F5F5;
					color: #181D21;
					border-radius: 6px;
					margin-top: 4px;
					margin-right: 4px;
					display: flex;
					justify-content: center;
					align-items: center;
					&:nth-child(3) {
						margin-right: 0;
					}
					&:nth-child(6) {
						margin-right: 0;
					}

					.item-desc {
						.item-title {
							font-weight: 600;
							font-size: 16px;
						}

						.item-content {
							display: flex;
							justify-content: center;
							margin-top: 6px;
							font-weight: 400;
							font-size: 12px;
							color: #535557;
						}
					}
				}

				.weather-active {
					background: #00B23C !important;

					.item-title {
						color: #fff;
					}

					.item-content {
						color: #fff !important;
					}
				}
			}

			.phenomena-chart {
				margin-top: 20px;
				height: 200px;
				width: 100%;
			}
		}

		.insect-container {
			box-sizing: border-box;
			padding: 16px 12px;
			margin-top: 10px;
			height: 330px;
			background: #fff;
			box-shadow: 0px 3px 12px 0px rgba(0, 0, 0, 0.02);
			border-radius: 8px 8px 8px 8px;

			.phenomena-tabs {
				justify-content: space-between;
				display: flex;
				align-items: center;
				height: 20px;

				.phenomena-tabs-box {
					display: flex;
					align-items: center;
					height: 20px;
				}

				.tabs-item {
					width: 60px;
					height: 15px;
					font-weight: 500;
					font-size: 15px;
					color: #535557;
					line-height: 15px;
					margin-right: 16px;
				}

				.activeTab {
					position: relative;
					color: #00B23C;

					&::after {
						position: absolute;
						bottom: -4px;
						left: 0;
						content: '';
						width: 59px;
						height: 2px;
						background: #00B23C;
						border-radius: 2px 2px 2px 2px;
					}
				}
			}

			.equipmen-type {
				margin-top: 12px;
				margin-bottom: 12px;
				height: 12px;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.equipmen-type-left {
					font-size: 12px;
					color: #181B21;
				}

				.equipmen-type-time {
					font-size: 12px;
					color: #A1A3A5;
				}
			}

			.notice {
				margin-top: 10px;
			}
			.swiper {
				border-radius: 6px;
				overflow: hidden;
				width: 100%;
				height: 180px;
				img {
					width: 100%;
					height: 100%;
				}
			}
			.nodata {
				height: 500rpx;
			}
			.tags {
				display: grid;
				           grid-template-columns: repeat(4,1fr);
				           gap: 8rpx;
				           /* 设置左对齐 */
				           justify-content: start;
				margin: 10px 0;
				min-height: 30px;
				color: #181B21;
				font-size: 12px;
				.tags-item {
					padding: 0 4px;
					box-sizing: border-box;
					margin-right: 8px;
					display: flex;
					justify-content: center;
					align-items: center;
					height: 30px;
					background: #F5F5F5;
					border-radius: 4px;
				}
				.activeTag {
					background: #E0F6E7;
					color: #00B23C;
				}
			}
		}
		
	}
	::v-deep .uni-date-x--border {
		border-radius: 20px;
		overflow: hidden;
	}
	.no-data {
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>